using CommunityToolkit.Mvvm.Messaging;
using ImageCSharp.Core.Interfaces;
using ImageCSharp.Core.Services;
using ImageCSharp.ViewModels;
using ImageCSharp.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using System.Windows;

namespace ImageCSharp
{
    public partial class App : System.Windows.Application
    {
        public static IHost _host { get; private set; }

        public IServiceProvider ServiceProvider { get; private set; }

        public static ILoggerFactory? LoggerFactory { get; private set; }

        protected async void OnStartup(object sender, StartupEventArgs e)
        {
            //base.OnStartup(e);

            // 创建主机
            _host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    ConfigureServices(services);
                })
                .ConfigureLogging(logging =>
                {
                    logging.AddConsole();
                    logging.AddDebug();
                    logging.SetMinimumLevel(LogLevel.Information);
                })
                .Build();

            // Configure services
            var services = new ServiceCollection();
            ConfigureServices(services);

            LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
            {
                builder.AddConsole();
                builder.SetMinimumLevel(LogLevel.Information);
            });
            // 确保Plugins目录存在
            EnsurePluginsDirectory();
			
            // 初始化插件系统
            var pluginService = _host.Services.GetRequiredService<PluginService>();
            pluginService.Initialize();

            ServiceProvider = services.BuildServiceProvider();

            // Create and show main window
            //var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
            //mainWindow.Show();

            // 启动主机
            await _host.StartAsync();

            // 显示主窗口
            var mainWindow = _host.Services.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }

        private void ConfigureServices(IServiceCollection services)
        {
            // 注册服务
            services.AddSingleton<IImageService, ImageService>();
            services.AddSingleton<IPluginService, PluginService>();
            services.AddSingleton<IToolService, ToolService>();
            services.AddSingleton<IHistoryService, HistoryService>();
            services.AddSingleton<IBatchProcessingService, BatchProcessingService>();
            services.AddSingleton<IMessenger, WeakReferenceMessenger>();

            services.AddSingleton<ImageService>();
            services.AddSingleton<PluginService>(provider =>
                new PluginService(
            ));

            services.AddSingleton<ToolService>(provider =>
                new ToolService(
                    provider.GetRequiredService<IMessenger>()
                )
            );
            services.AddSingleton<HistoryService>();
            services.AddSingleton<BatchProcessingService>(provider =>
                new BatchProcessingService(
                    provider.GetRequiredService<ImageService>(),
                    provider.GetRequiredService<PluginService>()
                )
            );

            // ViewModels
            services.AddSingleton<MainViewModel>(provider =>
                new MainViewModel(
                    provider.GetRequiredService<ImageService>(),
                    provider.GetRequiredService<PluginService>(),
                    provider.GetRequiredService<ToolService>(),
                    provider.GetRequiredService<HistoryService>(),
                    provider.GetRequiredService<BatchProcessingService>()
                )
            );

            // 注册主窗口
            services.AddTransient<MainWindow>(provider =>
                new MainWindow(
                    provider.GetRequiredService<MainViewModel>()
                )
                );
        }
		
		
        private void EnsurePluginsDirectory()
        {
            var pluginsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
            if (!Directory.Exists(pluginsDir))
            {
                try
                {
                    Directory.CreateDirectory(pluginsDir);
                    Console.WriteLine($"Created plugins directory: {pluginsDir}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to create plugins directory: {ex.Message}");
                }
            }
        }
    }
}
